<template>
  <div class="container">
    <!-- 添加学科对话框 -->
    <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="学科名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入学科名称"></el-input>
      </el-form-item>

      <el-form-item label="是否显示" prop="switch">
        <el-switch v-model="form.switch" active-color="#13ce66" inactive-color="#ff4949"></el-switch>
      </el-form-item>

      <el-form-item>
        <el-button @click="onCancel">取消</el-button>
        <el-button type="primary" @click="onSubmit">确认</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { add as addSubjectAPI, update as updateSubjectAPI, detail } from '@/api/hmmm/subjects'
export default {
  name: 'SubjectsAdd',
  props: {
    // 接收父级的 id
    parentId: {
      type: [Number, String],
      required: true
    },
    isEdit: {
      type: Boolean,
      required: true
    }
  },
  data () {
    return {
      query: '', // 查询字符串参数
      form: {
        name: '',
        switch: true
      },
      rules: {
        name: [
          { required: true, message: '请输入学科名称', trigger: 'blur' },
          {
            min: 1,
            max: 10,
            message: '长度在 1 到 10 个字符',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  async created () {
    // 父组件点击修改时数据回显
    if (this.isEdit) {
      const res = await detail({ id: this.parentId })
      // console.log(res)
      this.form.name = res.data.subjectName
    }
  },
  methods: {

    // 取消--关闭弹窗
    onCancel () {
      this.$emit('close')
    },

    // 新增学科
    async addSubFn () {
      await addSubjectAPI({
        subjectName: this.form.name,
        isFrontDisplay: this.form.switch
      })
    },
    // 编辑学科
    async editSubFn () {
      await updateSubjectAPI({
        id: this.parentId,
        subjectName: this.form.name,
        isFrontDisplay: this.form.switch
      })
    },

    // 确定--兜底校验
    onSubmit () {
      // console.log('submit!')
      this.$refs.form.validate(async valid => {
        if (!valid) return
        // 验证通过--新增学科/编辑学科
        this.isEdit ? this.editSubFn() : this.addSubFn()
        // 给用户提示
        this.$message.success('操作成功')
        // 刷新列表
        // 关闭弹框
        this.$emit('updata-list')
      })
    },

    // 表单重置
    resetForm () {
      this.form.name = ''
      this.$refs.form.resetFields()
    }

  }
}
</script>

<style scoped lang='less'></style>
